package services

import (
	"context"
	"encoding/json"
	"fmt"
	"net/url"
	"strings"
	"time"

	"gitee.com/wangshh_123/cross-pay-go/src/database"
	"gitee.com/wangshh_123/cross-pay-go/src/models"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/hlPay"
	hlpaymodels "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/hlPay/models"
	photonpaymodels "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/models"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/common"
)

// GetCardBin 获取卡Bin信息并转换为PhotonPay格式，但保留CardBinId字段
// 参数:
//   - client: HlPay客户端
//
// 返回:
//   - *photonpay.models.CardBinResponse: PhotonPay格式的卡Bin响应（包含CardBinId）
//   - error: 错误信息
func GetCardBin(ctx context.Context, client *hlPay.HlPayClient) (*photonpaymodels.CardBinResponse, error) {
	// 调用API获取卡Bin信息
	respBody, err := client.Get(ctx, "/hlPayApi/card/getCarBin")
	if err != nil {
		return nil, fmt.Errorf("获取卡Bin信息失败: %v", err)
	}

	// 解析HlPay响应
	var hlpayResponse hlpaymodels.CardBinResponse
	if err := json.Unmarshal(respBody, &hlpayResponse); err != nil {
		return nil, fmt.Errorf("解析卡Bin响应失败: %v", err)
	}

	// 检查响应状态
	if hlpayResponse.Code != 200 {
		return nil, fmt.Errorf("获取卡Bin信息失败，错误码: %d，错误信息: %s", hlpayResponse.Code, hlpayResponse.Msg)
	}

	// 转换为PhotonPay格式
	photonpayResponse := &photonpaymodels.CardBinResponse{
		BaseResponse: photonpaymodels.BaseResponse{
			Code: "0000", // 使用0000作为成功码
			Msg:  json.RawMessage(`"success"`),
		},
		Data: make([]photonpaymodels.CardBinInfo, 0, len(hlpayResponse.Data.BinList)),
	}

	// 转换每个卡bin信息
	for _, hlpayBin := range hlpayResponse.Data.BinList {
		photonpayBin := photonpaymodels.CardBinInfo{
			BillingAddressUpdatable: "Y", // 使用Y/F格式，HlPay默认支持账单地址更新
			CardBin:                 hlpayBin.Bin,
			CardBinId:               hlpayBin.CardBinId, // 保留HlPay的CardBinId字段
			CardCurrency:            "USD",              // HlPay默认USD，可根据实际情况调整
			CardScheme:              hlpayBin.Network,   // 使用Network字段作为卡组织
			CardType:                "recharge",         // HlPay默认常规卡
			ExpiryDateCustomization: "F",                // 使用Y/F格式，HlPay不支持自定义过期时间
			RemainingAvailableCard:  "0",                // HlPay没有这个信息，设为0
			AvailableCard:           "0",                // HlPay没有这个信息，设为0
			CardFormFactor:          "virtual_card",     // HlPay默认虚拟卡
		}

		// 根据HlPay的Network字段映射卡组织，使用大写格式
		switch hlpayBin.Network {
		case "VISA":
			photonpayBin.CardScheme = "VISA"
		case "MASTERCARD":
			photonpayBin.CardScheme = "MASTERCARD"
		case "DISCOVER":
			photonpayBin.CardScheme = "DISCOVER"
		case "AMEX":
			photonpayBin.CardScheme = "AMEX"
		default:
			photonpayBin.CardScheme = strings.ToUpper(hlpayBin.Network)
		}

		// 根据HlPay的BinStatus判断卡bin状态
		if hlpayBin.BinStatus == "1" {
			// 如果卡bin被冻结，设置可用卡数为0
			photonpayBin.RemainingAvailableCard = "0"
			photonpayBin.AvailableCard = "0"
		}

		// 根据HlPay的HasHot字段判断是否为热门卡
		if hlpayBin.HasHot == "Y" {
			// 热门卡可能有更多可用卡数，这里设为1000作为示例
			photonpayBin.RemainingAvailableCard = "1000"
			photonpayBin.AvailableCard = "1000"
		}

		photonpayResponse.Data = append(photonpayResponse.Data, photonpayBin)
	}

	return photonpayResponse, nil
}

// GetStateList 获取州列表
// 参数:
//   - client: HlPay客户端
//
// 返回:
//   - *models.StateResponse: 州列表响应
//   - error: 错误信息
func GetStateList(ctx context.Context, client *hlPay.HlPayClient) (*hlpaymodels.StateResponse, error) {
	// 调用API获取州列表
	respBody, err := client.Get(ctx, "/hlPayApi/card/getState")
	if err != nil {
		return nil, fmt.Errorf("获取州列表失败: %v", err)
	}

	// 解析响应
	var response hlpaymodels.StateResponse
	if err := json.Unmarshal(respBody, &response); err != nil {
		return nil, fmt.Errorf("解析州列表响应失败: %v", err)
	}

	// 检查响应状态
	if response.Code != 200 {
		return nil, fmt.Errorf("获取州列表失败，错误码: %d，错误信息: %s", response.Code, response.Msg)
	}

	return &response, nil
}

// GetCardList gets the card list from HlPay.
func GetCardList(ctx context.Context, client *hlPay.HlPayClient, pageNum, pageSize int, params *hlpaymodels.CardListRequest) (*hlpaymodels.CardListResponse, error) {
	// Construct URL with query parameters
	path := fmt.Sprintf("/hlPayApi/card/list?pageNum=%d&pageSize=%d", pageNum, pageSize)

	// Prepare form data
	formData := url.Values{}
	if params.CardNo != "" {
		formData.Set("cardNo", params.CardNo)
	}
	if params.Name != "" {
		formData.Set("name", params.Name)
	}
	if params.Status != "" {
		formData.Set("status", params.Status)
	}

	// Make the API call
	respBody, err := client.PostForm(ctx, path, formData)
	if err != nil {
		return nil, fmt.Errorf("获取卡列表失败: %v", err)
	}

	// Parse the response
	var response hlpaymodels.CardListResponse
	if err := json.Unmarshal(respBody, &response); err != nil {
		return nil, fmt.Errorf("解析卡列表响应失败: %v", err)
	}

	// Check response code
	if response.Code != 200 {
		return nil, fmt.Errorf("获取卡列表失败，错误码: %d，错误信息: %s", response.Code, response.Message)
	}

	// 标准化响应格式
	standardizeHlPayCardListResponse(&response)

	return &response, nil
}

// standardizeHlPayCardListResponse 标准化HlPay卡列表响应格式
// 将响应格式标准化为：code使用"0000"，卡组织使用大写，状态转换为统一状态
func standardizeHlPayCardListResponse(response *hlpaymodels.CardListResponse) {
	// 确保成功码为"0000"
	if response.Code == 200 {
		response.Code = 0 // HlPay使用0表示成功
	}

	// 标准化每个卡片信息
	for i := range response.Rows {
		card := &response.Rows[i]

		// 转换卡状态为统一状态
		if card.Status != "" {
			// 使用统一状态映射工具
			card.Status = common.MapPlatformStatusToUnified("hlpay", card.Status)
		}

		// 标准化开卡状态（如果需要）
		if card.OpenCardStatus != "" {
			card.OpenCardStatus = strings.ToUpper(card.OpenCardStatus)
		}
	}
}

// GetCardDetail gets the details of a specific card from HlPay.
func GetCardDetail(ctx context.Context, client *hlPay.HlPayClient, cardID string) (*hlpaymodels.CardDetailResponse, error) {
	// Construct the path with the card ID
	path := fmt.Sprintf("/hlPayApi/card/getCardDetail/%s", cardID)

	// Make the API call
	respBody, err := client.Get(ctx, path)
	if err != nil {
		return nil, fmt.Errorf("获取卡详情失败: %v", err)
	}

	// Parse the response
	var response hlpaymodels.CardDetailResponse
	if err := json.Unmarshal(respBody, &response); err != nil {
		return nil, fmt.Errorf("解析卡详情响应失败: %v", err)
	}

	// Check the response code
	if response.Code != 200 {
		return nil, fmt.Errorf("获取卡详情失败，错误码: %d，错误信息: %s", response.Code, response.Msg)
	}

	return &response, nil
}

// OpenCard opens a new card with the given parameters.
func OpenCard(ctx context.Context, client *hlPay.HlPayClient, params *hlpaymodels.OpenCardRequest) (*hlpaymodels.OpenCardResponse, error) {
	// 创建传递给第三方的请求结构体，过滤掉nickname字段
	thirdPartyParams := &hlpaymodels.ThirdPartyOpenCardRequest{
		CardAddress: params.CardAddress,
		Zip:         params.Zip,
		LastName:    params.LastName,
		Cost:        params.Cost,
		City:        params.City,
		Bin:         params.Bin,
		BatchCount:  params.BatchCount,
		FirstName:   params.FirstName,
		BillAddress: params.BillAddress,
		CardBinID:   params.CardBinID,
		Phone:       params.Phone,
		State:       params.State,
		Email:       params.Email,
	}

	// Make the API call
	respBody, err := client.Post(ctx, "/hlPayApi/card/openCard", thirdPartyParams)
	if err != nil {
		return nil, fmt.Errorf("开卡失败: %v", err)
	}

	// Parse the response
	var response hlpaymodels.OpenCardResponse
	if err := json.Unmarshal(respBody, &response); err != nil {
		return nil, fmt.Errorf("解析开卡响应失败: %v", err)
	}

	// Check the response code
	if response.Code != 200 {
		return nil, fmt.Errorf("开卡失败，错误码: %d，错误信息: %s", response.Code, response.Msg)
	}

	return &response, nil
}

// BatchOpenCards opens multiple cards in a batch. 批量开卡
func BatchOpenCards(ctx context.Context, client *hlPay.HlPayClient, params *hlpaymodels.BatchOpenCardRequest) (*hlpaymodels.BatchOpenCardResponse, error) {
	// 创建传递给第三方的请求结构体，过滤掉nickname字段
	thirdPartyParams := &hlpaymodels.ThirdPartyOpenCardRequest{
		CardAddress: params.CardAddress,
		Zip:         params.Zip,
		LastName:    params.LastName,
		Cost:        params.Cost,
		City:        params.City,
		Bin:         params.Bin,
		BatchCount:  params.BatchCount,
		FirstName:   params.FirstName,
		BillAddress: params.BillAddress,
		CardBinID:   params.CardBinID,
		Phone:       params.Phone,
		State:       params.State,
		Email:       params.Email,
	}

	// Make the API call to the batch endpoint
	respBody, err := client.Post(ctx, "/hlPayApi/card/openCards", thirdPartyParams)
	if err != nil {
		return nil, fmt.Errorf("批量开卡失败: %v", err)
	}

	// Parse the response
	var response hlpaymodels.BatchOpenCardResponse
	if err := json.Unmarshal(respBody, &response); err != nil {
		return nil, fmt.Errorf("解析批量开卡响应失败: %v", err)
	}

	// Check the response code
	if response.Code != 200 {
		return nil, fmt.Errorf("批量开卡失败，错误码: %d，错误信息: %s", response.Code, response.Msg)
	}

	return &response, nil
}

// GetCardTask 查询开卡任务
// 参数:
//   - client: HlPay客户端
//   - taskID: 任务ID
//
// 返回:
//   - *models.GetCardTaskResponse: 开卡任务响应
//   - error: 错误信息
func GetCardTask(ctx context.Context, client *hlPay.HlPayClient, taskID string) (*hlpaymodels.GetCardTaskResponse, error) {
	// 构造API路径
	path := fmt.Sprintf("/hlPayApi/card/task/%s", taskID)

	// 调用API获取开卡任务信息
	respBody, err := client.Get(ctx, path)
	if err != nil {
		return nil, fmt.Errorf("查询开卡任务失败: %v", err)
	}

	// 解析响应
	var response hlpaymodels.GetCardTaskResponse
	if err := json.Unmarshal(respBody, &response); err != nil {
		return nil, fmt.Errorf("解析开卡任务响应失败: %v", err)
	}

	// 检查响应状态
	if response.Code != 200 {
		return nil, fmt.Errorf("查询开卡任务失败，错误码: %d，错误信息: %s", response.Code, response.Msg)
	}

	return &response, nil
}

// Recharge recharges a card. 充值
func Recharge(ctx context.Context, client *hlPay.HlPayClient, params *hlpaymodels.RechargeRequest) (*hlpaymodels.RechargeResponse, error) {
	// Make the API call
	respBody, err := client.Put(ctx, "/hlPayApi/card/recharge", params)
	if err != nil {
		return nil, fmt.Errorf("充值失败: %v", err)
	}

	// Parse the response
	var response hlpaymodels.RechargeResponse
	if err := json.Unmarshal(respBody, &response); err != nil {
		return nil, fmt.Errorf("解析充值响应失败: %v", err)
	}

	// Check the response code
	if response.Code != 200 {
		return nil, fmt.Errorf("充值失败，错误码: %d，错误信息: %s", response.Code, response.Msg)
	}

	return &response, nil
}

// Withdraw withdraws from a card. 退款
func Withdraw(ctx context.Context, client *hlPay.HlPayClient, params *hlpaymodels.WithdrawRequest) (*hlpaymodels.WithdrawResponse, error) {
	// Make the API call
	respBody, err := client.Put(ctx, "/hlPayApi/card/withdraw", params)
	if err != nil {
		return nil, fmt.Errorf("提现失败: %v", err)
	}

	// Parse the response
	var response hlpaymodels.WithdrawResponse
	if err := json.Unmarshal(respBody, &response); err != nil {
		return nil, fmt.Errorf("解析提现响应失败: %v", err)
	}

	// Check the response code
	if response.Code != 200 {
		return nil, fmt.Errorf("提现失败，错误码: %d，错误信息: %s", response.Code, response.Msg)
	}

	return &response, nil
}

// GetCardTransactionDetail 获取卡交易详情
func GetCardTransactionDetail(ctx context.Context, client *hlPay.HlPayClient, params *hlpaymodels.CardTransactionDetailRequest) (*hlpaymodels.CardTransactionDetailResponse, error) {
	formData := url.Values{}
	if params.CardId != "" {
		formData.Set("cardId", params.CardId)
	}
	if params.CardNo != "" {
		formData.Set("params[cardNo]", params.CardNo)
	}
	if params.Status != "" {
		formData.Set("params[status]", params.Status)
	}
	if params.TransactionType != "" {
		formData.Set("params[transactionType]", params.TransactionType)
	}
	if params.BeginTime != "" {
		formData.Set("params[beginTime]", params.BeginTime)
	}
	if params.EndTime != "" {
		formData.Set("params[endTime]", params.EndTime)
	}

	respBody, err := client.GetForm(ctx, "/hlPayApi/transaction/getCardTransaction", formData)
	if err != nil {
		return nil, fmt.Errorf("获取卡交易详情失败: %v", err)
	}

	var response hlpaymodels.CardTransactionDetailResponse
	if err := json.Unmarshal(respBody, &response); err != nil {
		return nil, fmt.Errorf("解析卡交易详情响应失败: %v", err)
	}

	if response.Code != 200 {
		return nil, fmt.Errorf("获取卡交易详情失败，错误码: %d，错误信息: %s", response.Code, response.Msg)
	}

	return &response, nil
}

// FreezeCard freezes a card.
func FreezeCard(ctx context.Context, client *hlPay.HlPayClient, cardID string) (*hlpaymodels.FreezeCardResponse, error) {
	// Construct the path with the card ID
	path := fmt.Sprintf("/hlPayApi/card/freeze/%s", cardID)

	// Make the API call
	respBody, err := client.Put(ctx, path, nil)
	if err != nil {
		return nil, fmt.Errorf("冻结卡片失败: %v", err)
	}

	// Parse the response
	var response hlpaymodels.FreezeCardResponse
	if err := json.Unmarshal(respBody, &response); err != nil {
		return nil, fmt.Errorf("解析冻结卡片响应失败: %v", err)
	}

	// Check the response code
	if response.Code != 200 {
		return nil, fmt.Errorf("冻结卡片失败，错误码: %d，错误信息: %s", response.Code, response.Msg)
	}

	return &response, nil
}

// EnableCard enables a card.
func EnableCard(ctx context.Context, client *hlPay.HlPayClient, cardID string) (*hlpaymodels.EnableCardResponse, error) {
	// Construct the path with the card ID
	path := fmt.Sprintf("/hlPayApi/card/enable/%s", cardID)

	// Make the API call
	respBody, err := client.Put(ctx, path, nil)
	if err != nil {
		return nil, fmt.Errorf("解冻卡片失败: %v", err)
	}

	// Parse the response
	var response hlpaymodels.EnableCardResponse
	if err := json.Unmarshal(respBody, &response); err != nil {
		return nil, fmt.Errorf("解析解冻卡片响应失败: %v", err)
	}

	// Check the response code
	if response.Code != 200 {
		return nil, fmt.Errorf("解冻卡片失败，错误码: %d，错误信息: %s", response.Code, response.Msg)
	}

	return &response, nil
}

// CancelCard cancels a card.
func CancelCard(ctx context.Context, client *hlPay.HlPayClient, cardID string) (*hlpaymodels.CancelCardResponse, error) {
	// Construct the path with the card ID
	path := fmt.Sprintf("/hlPayApi/card/remove/%s", cardID)

	// Make the API call
	respBody, err := client.Delete(ctx, path)
	if err != nil {
		return nil, fmt.Errorf("注销卡片失败: %v", err)
	}

	// Parse the response
	var response hlpaymodels.CancelCardResponse
	if err := json.Unmarshal(respBody, &response); err != nil {
		return nil, fmt.Errorf("解析注销卡片响应失败: %v", err)
	}

	// Check the response code
	if response.Code != 200 {
		return nil, fmt.Errorf("注销卡片失败，错误码: %d，错误信息: %s", response.Code, response.Msg)
	}

	return &response, nil
}

// GetVerificationCode gets the verification codes for a card.
func GetVerificationCode(ctx context.Context, client *hlPay.HlPayClient, cardID string) (*hlpaymodels.VerificationCodeResponse, error) {
	// Construct the path with the card ID
	path := fmt.Sprintf("/hlPayApi/card/verification/code/%s", cardID)

	// Make the API call
	respBody, err := client.Get(ctx, path)
	if err != nil {
		return nil, fmt.Errorf("获取卡片验证码失败: %v", err)
	}

	// Parse the response
	var response hlpaymodels.VerificationCodeResponse
	if err := json.Unmarshal(respBody, &response); err != nil {
		return nil, fmt.Errorf("解析卡片验证码响应失败: %v", err)
	}

	// Check the response code
	if response.Code != 200 {
		return nil, fmt.Errorf("获取卡片验证码失败，错误码: %d，错误信息: %s", response.Code, response.Msg)
	}

	return &response, nil
}

// GetCardHistoryList 获取HlPay卡历史列表
// 从本地数据库 hlpay_card_open_records 表中查询卡历史记录
func GetCardHistoryList(ctx context.Context, client *hlPay.HlPayClient, params *hlpaymodels.CardHistoryListRequest) (*hlpaymodels.CardHistoryListResponse, error) {
	fmt.Printf("[GetCardHistoryList] 开始处理卡历史查询请求\n")

	// 获取数据库连接
	db := database.DB
	if db == nil {
		fmt.Printf("[GetCardHistoryList] 错误：数据库连接失败\n")
		return nil, fmt.Errorf("数据库连接失败")
	}
	fmt.Printf("[GetCardHistoryList] 数据库连接成功\n")

	// 从上下文中获取用户ID
	var userID int64
	if userIDValue := ctx.Value("user_id"); userIDValue != nil {
		fmt.Printf("[GetCardHistoryList] 从上下文获取到用户ID值: %v (类型: %T)\n", userIDValue, userIDValue)
		switch v := userIDValue.(type) {
		case int64:
			userID = v
		case float64:
			userID = int64(v)
		case int:
			userID = int64(v)
		default:
			fmt.Printf("[GetCardHistoryList] 错误：用户信息类型错误: %T\n", userIDValue)
			return nil, fmt.Errorf("用户信息类型错误: %T", userIDValue)
		}
		fmt.Printf("[GetCardHistoryList] 解析后的用户ID: %d\n", userID)
	} else {
		fmt.Printf("[GetCardHistoryList] 错误：用户信息不存在\n")
		return nil, fmt.Errorf("用户信息不存在")
	}

	// 构建查询
	query := db.Model(&models.HlpayCardOpenRecord{})
	fmt.Printf("[GetCardHistoryList] 开始构建查询，用户ID: %d\n", userID)

	// 添加用户权限过滤
	query = query.Where("user_id = ?", userID)

	// 状态映射：前端传 succeed 实际查 success
	status := params.Status
	if status == "succeed" {
		status = "success"
	}
	if status != "" {
		query = query.Where("status = ?", status)
	}
	// 其余过滤条件
	if params.CardID != "" {
		query = query.Where("card_id = ?", params.CardID)
	}
	if params.CardFormFactor != "" {
		query = query.Where("card_form_factor = ?", params.CardFormFactor)
	}
	if params.FeeType != "" {
		query = query.Where("fee_type = ?", params.FeeType)
	}
	// 处理日期范围查询
	if params.CreatedAtStart != "" {
		// 尝试解析日期格式
		startTime, err := time.Parse("2006-01-02", params.CreatedAtStart)
		if err != nil {
			// 尝试解析带时间的格式
			startTime, err = time.Parse("2006-01-02T15:04:05", params.CreatedAtStart)
			if err != nil {
				fmt.Printf("[GetCardHistoryList] 警告：无法解析开始日期格式: %s\n", params.CreatedAtStart)
			}
		}
		if err == nil {
			query = query.Where("created_at >= ?", startTime)
			fmt.Printf("[GetCardHistoryList] 添加开始时间过滤: %s\n", startTime.Format("2006-01-02 15:04:05"))
		}
	}

	if params.CreatedAtEnd != "" {
		// 尝试解析日期格式
		endTime, err := time.Parse("2006-01-02", params.CreatedAtEnd)
		if err != nil {
			// 尝试解析带时间的格式
			endTime, err = time.Parse("2006-01-02T15:04:05", params.CreatedAtEnd)
			if err != nil {
				fmt.Printf("[GetCardHistoryList] 警告：无法解析结束日期格式: %s\n", params.CreatedAtEnd)
			}
		}
		if err == nil {
			// 将结束日期设置为当天的最后一秒
			endTime = endTime.Add(24*time.Hour - time.Second)
			query = query.Where("created_at <= ?", endTime)
			fmt.Printf("[GetCardHistoryList] 添加结束时间过滤: %s\n", endTime.Format("2006-01-02 15:04:05"))
		}
	}

	// 获取总数
	var total int64
	fmt.Printf("[GetCardHistoryList] 开始查询总数\n")
	if err := query.Count(&total).Error; err != nil {
		fmt.Printf("[GetCardHistoryList] 错误：查询总数失败: %v\n", err)
		return nil, fmt.Errorf("查询总数失败: %v", err)
	}
	fmt.Printf("[GetCardHistoryList] 查询到总记录数: %d\n", total)

	// 分页查询
	var records []models.HlpayCardOpenRecord
	offset := (params.PageIndex - 1) * params.PageSize
	fmt.Printf("[GetCardHistoryList] 开始分页查询，页码: %d, 每页大小: %d, 偏移量: %d\n", params.PageIndex, params.PageSize, offset)

	if err := query.Order("created_at DESC").
		Offset(int(offset)).
		Limit(int(params.PageSize)).
		Find(&records).Error; err != nil {
		fmt.Printf("[GetCardHistoryList] 错误：查询卡历史记录失败: %v\n", err)
		return nil, fmt.Errorf("查询卡历史记录失败: %v", err)
	}
	fmt.Printf("[GetCardHistoryList] 查询到记录数: %d\n", len(records))

	// 转换为响应格式
	data := make([]hlpaymodels.CardHistoryInfo, len(records))
	for i, record := range records {
		fmt.Printf("[GetCardHistoryList] 处理记录 %d: CardID=%s, Status=%s\n", i+1, record.CardID, record.Status)
		data[i] = hlpaymodels.CardHistoryInfo{
			ActualFeeAmount:   record.ActualFeeAmount.String(),
			ActualFeeCurrency: record.ActualFeeCurrency,
			CardID:            record.CardID,
			CardScheme:        record.CardScheme,
			CardType:          record.CardType,
			CreatedAt:         record.CreatedAt.Format("2006-01-02T15:04:05"),
			FeeType:           record.FeeType,
			MaskCardNo:        record.MaskCardNo,
			MemberID:          record.MemberID,
			MatrixAccount:     record.MatrixAccount,
			Nickname:          record.Nickname,
			ReferenceNo:       record.ReferenceNo,
			Status:            record.Status,
			CardFormFactor:    record.CardFormFactor,
			CardNickname:      record.CardNickname,
		}
	}

	// 构建响应
	response := &hlpaymodels.CardHistoryListResponse{
		BaseResponse: hlpaymodels.BaseResponse{
			Code: "0000",
			Msg:  "success",
		},
		PageIndex: params.PageIndex,
		PageSize:  params.PageSize,
		Total:     total,
		Data:      data,
	}

	fmt.Printf("[GetCardHistoryList] 查询完成，返回 %d 条记录\n", len(data))
	return response, nil
}
